<?php
namespace app\api\controller;
use alipay\Alipay;
use think\Db;

class Ali extends Base {

    //阿里云授权登录
    public function oauth() {
        $param = input('param.');
        if($param) {
            if(isset($param['auth_code'])) {
                $alipay = new Alipay(config('alipay_config'));
                //获取access_token
                $access_token = $alipay->getAccessToken($param['auth_code']);
                // 40002 授权码code无效 40004
                if($access_token !== false) {
                    $result_array = $alipay->userinfoShare($access_token);
                    if(isset($result_array['alipay_user_info_share_response'])) {
//                    mylog($this->cmd,var_export($result_array,true),'alipay_success.log');
                        $response = $result_array['alipay_user_info_share_response'];

                        $response['gender'] = isset($response['gender']) ? $response['gender'] : '0';
                        $response['nick_name'] = isset($response['nick_name']) ? $response['nick_name'] : '';
                        $user_data = [
                            'avatar' => $response['avatar'],
                            'city' => $response['city'],
                            'gender' => $response['gender'],
                            'nick_name' => $response['nick_name'],
                            'province' => $response['province'],
                            'user_id' => $response['user_id']
                        ];
                        $whereUser = [
                            ['user_id','=',$response['user_id']]
                        ];
                        $user_exist = Db::table('mp_user_alipay')->where($whereUser)->find();
                        $time = time();
                        $uid = '';
                        //更新或新增支付宝用户表
                        if($user_exist) {
                            $user_data['update_time'] = $time;
                            Db::table('mp_user_alipay')->where($whereUser)->update($user_data);
                            if($user_exist['uid']) {
                               $uid = $user_exist['uid'];
                            }
                        }else {
                            $user_data['create_time'] = $time;
                            Db::table('mp_user_alipay')->where($whereUser)->insertGetId($user_data);
                        }

                        $token = md5($response['user_id'] . $time);
                        /*
                         * 支持三种方式同时登录, 每种方式同一时间仅能一人登录
                         * 已有当前登录方式token则更新, 没有则新增
                         */
                        $whereToken = [
                            ['alipay_user_id','=',$response['user_id']]
                        ];
                        $token_exist = Db::table('mp_token')->where($whereToken)->find();
                        if(!$token_exist) {
                            $insert_data = [
                                'alipay_user_id' => $response['user_id'],
                                'token' => $token,
                                'create_time' => $time,
                                'login_type' => 3
                            ];
                            if($uid) {
                                $insert_data['uid'] = $uid;
                            }
                            Db::table('mp_token')->insert($insert_data);
                        }else {
                            $update_data = [
                                'alipay_user_id' => $response['user_id'],
                                'token' => $token,
                                'create_time' => $time,
                                'login_type' => 3
                            ];
                            if($uid) {
                                $update_data['uid'] = $uid;
                            }
                            Db::table('mp_token')->where($whereToken)->update($update_data);
                        }
                        if(isset($param['backurl'])) {
                            $query_data = [
                                'alipay_user_id' => $response['user_id'],
                                'uid' => $uid,
                                'token' => $token
                            ];
                            $backurl = url_reset($param['backurl'],$query_data);
                            header('Location:'. $backurl);exit();
                        }
                        exit('login success');
                    }else {
                        mylog($this->cmd,var_export($result_array,true),'alipay_error.log');
                        exit('授权登录失败');
                    }
                }else {
                    exit('获取token失败');
                }
            }else {
                if(isset($param['backurl'])) {
                    $backurl = '?backurl=' . urlencode($param['backurl']);
                }else {
                    $backurl = '';
                }
                $appid = config('alipay_config')['app_id'];
                $scope = 'auth_user'; //auth_code
                $redirect_url = $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] . '/api/ali/oauth' . $backurl;
                $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$appid.'&scope='.$scope.'&redirect_uri=' . urlencode($redirect_url);
                header('Location:'. $url);exit();
            }
        }else {
            echo '登录授权';
        }

    }


    //阿里云静默授权获取alipay_user_id
    public function oauth2() {
        $param = input('param.');
        if($param) {
            if(isset($param['auth_code'])) {
                $alipay = new Alipay(config('alipay_config'));
                //获取access_token
                $response = $alipay->getAuthBase($param['auth_code']);
                // 40002 授权码code无效 40004
                if($response !== false) {
                    if(isset($param['backurl'])) {
                        $query_data = [
                            'alipay_user_id' => $response['user_id'],
                        ];
                        $backurl = url_reset($param['backurl'],$query_data);
                        mylog('oauth2',$backurl);
                        header('Location:'. $backurl);exit();
                    }else {
                        exit('login success');
                    }
                }else {
                    exit('auth_base失败');
                }
            }else {
                if(isset($param['backurl'])) {
                    $backurl = '?backurl=' . urlencode($param['backurl']);
                }else {
                    $backurl = '';
                }
                $appid = config('alipay_config')['app_id'];
                $scope = 'auth_base';
                $redirect_url = $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] . '/api/ali/oauth2' . $backurl;
                $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$appid.'&scope='.$scope.'&redirect_uri=' . urlencode($redirect_url);
                header('Location:'. $url);exit();
            }
        }else {
            echo '静默授权';
        }

    }
    





}